package com.itshare.video.common.config.interceptor;

import com.google.common.util.concurrent.RateLimiter;
import com.itshare.video.common.core.constant.enums.ApiInfo;
import com.itshare.video.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author lyr
 * @create 2020/10/12 20:24
 */
@Slf4j
@Component
@Lazy
public class RateLimitInterceptor implements HandlerInterceptor {

    /**
     * 每秒生成 500个令牌
     */
    private static final RateLimiter RATELIMITER = RateLimiter.create(500);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!RATELIMITER.tryAcquire()) {
            log.error("系统被限流了");
            //抛出异常
            throw new BusinessException(ApiInfo.BUSINESS_ERROR_BUSY);
        }
        return true;
    }
}
